package com.example.designpatterns.Interpreter;

import java.util.Stack;

/**
 * 计算器类（上下文）
 */
public class Calculator {

    //栈
    private Stack<Expression> stack = new Stack<>();

    /**
     * 解释文法方法
     */
    public int parse(String expression) {
        String[] elements = expression.split(" ");
        Expression leftExpr, rightExpr;

        for (int i = 0; i < elements.length; i++) {
            String operator = elements[i];
            if (("+".equals(operator) || "-".equals(operator))) {
                leftExpr = this.stack.pop();
                rightExpr = new NumExpression(Integer.valueOf(elements[++i]));
                if ("+".equals(operator)) {
                    this.stack.push(new AddExpression(leftExpr, rightExpr));
                } else if ("-".equals(operator)) {
                    this.stack.push(new SubExpression(leftExpr, rightExpr));
                }
            } else {
                NumExpression numInterpreter = new NumExpression(Integer.valueOf(elements[i]));
                this.stack.push(numInterpreter);
            }
        }
        //等价于new SubExpression(new AddExpression(new NumExpression(10), new NumExpression(30)), new NumExpression(20)).interpret()
        return this.stack.pop().interpret();
    }

}
